import React, { useEffect, useRef, useState } from "react";
import loading from "./loading.gif";
type PropsType = {
  src: string;
  width: number;
  height: number;
};

export const LazyloadImage: React.FC<PropsType> = ({ src, width, height }) => {
  const [url, setUrl] = useState(loading);
  const img = useRef<HTMLImageElement | null>(null);
  // 获取真实图片路径
  const getRealSrc = () => {
    const img = new Image();
    img.src = src;

    img.addEventListener("load", () => {
      setUrl(src);
    });

    img.addEventListener("error", () => {});
  };

  useEffect(() => {
    // IntersectionObserver 接口 (从属于Intersection Observer API) 提供了一种异步观察目标元素与其祖先元素或顶级文档视窗 (viewport) 交叉状态的方法
    const intersectionObserver = new IntersectionObserver(function (entries) {

      // 获取监听元素 触发的阈值
      const obj = entries[0];
      // 元素是否出现在视口之内
      if (obj.intersectionRatio > 0) {
        // 进入页面
        getRealSrc();
        // 取消监听
        img.current && intersectionObserver.unobserve(img.current);
      }
    });

    //  监听元素
    if (img.current) intersectionObserver.observe(img.current);
  }, []);

  return (
    <img
      ref={img}
      src={url}
      width={width}
      height={height}
      style={{ objectFit: "cover" }}
    />
  );
};
